package cn.dglydrpy.study.j2ee.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;

import cn.dglydrpy.study.j2ee.jdbc.utils.DBUtil;

public class LoginDemo {
	public static void main(String[] args) {
		
		Scanner in = new Scanner(System.in);
		while(true) {
			System.out.print("输入用户:");
			String name = in.nextLine();
			System.out.print("输入密码:");
			String password = in.nextLine();
			if(login(name, password)) {
				System.out.println("登录成功!");
				break;
			}
		}
	}
	
	public static boolean login(String username
			,String password){
		
		Connection conn = null;
		PreparedStatement stat = null;
		ResultSet rs = null;
		try {
			conn = DBUtil.getConn();
			
//使用statement有sql注入风险!!!
//			stat = conn.createStatement();
//			//拼接登录sql	
//			String sql = "select count(*) from user where "
//					+ "username='"+username
//					+"' and password='"+password+"'";
//			System.out.println(sql);
//			//执行sql
//			rs = stat.executeQuery(sql);
			
			String sql = "select count(*) from user where username=? and password=?";
			//创建sql执行对象并编译了sql
			stat = conn.prepareStatement(sql);
			stat.setString(1, username);
			stat.setString(2, password);
			
			//执行sql
			rs = stat.executeQuery();
			while(rs.next()){
				//因为查询结果里面只有一条数据所以直接写1
				return rs.getInt(1)==1;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(conn, stat, rs);
		}
		return false; //查不到数据或出错时返回false
	}
}
